import pygame,  os,  sys,  time,  random
from pygame.locals import *

class Timer(pygame.sprite.Sprite):
    
    def __init__(self,  playtime):
        pygame.sprite.Sprite.__init__(self)
        self.time = playtime
        self.starttime = int(round(time.time()))
        self.timeover = False
        self.timeacum = 0
        self.stringtime = self.get_string_time(playtime)
        self.font = pygame.font.Font(None,  48)
        self.image = self.font.render(self.stringtime, 1,  (0, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.center = (150,  70)
    
    def update(self):
        currenttime = int(round(time.time()))
        timeelapsed = currenttime - self.starttime
        if timeelapsed != self.timeacum:
            if timeelapsed > self.time:
                self.timeover = True
            else:
                self.timeacum = self.time - timeelapsed
                self.stringtime = self.get_string_time(self.timeacum)
                if (self.timeacum < 10):
                    self.image = self.font.render(self.stringtime,  1,  (255, 0, 0))
                else:
                    self.image = self.font.render(self.stringtime,  1,  (0, 0, 0))
                self.timeacum = timeelapsed
    
    def get_string_time(self,  time):
        minutes = int(time / 60)
        seconds = time - int(minutes*60)
        result_minutes = "00" + str(minutes)
        result_minutes = result_minutes[-2:]
        result_seconds = "00" + str(seconds)
        result_seconds = result_seconds[-2:]
        return result_minutes + ':' + result_seconds
        
